﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Books.Interfaces;
using Books.Model;
using Microsoft.Practices.Unity;

namespace Books.Web.ViewModels
{
    public class PublisherViewModel : IValidatableObject
    {
        [Required]
        public string City { get; set; }
     
        public Nullable<int> PublisherId { get; set; }
        
        [DisplayName("Publisher Name")]
        [Required]
        public string PublisherName { get; set; }

        [Dependency]
        public IPublisherApp PublisherApp { get; set; }

        public PublisherModel ToModel()
        {
            return new PublisherModel()
                {
                    City = City,
                    PublisherId = PublisherId.HasValue ? PublisherId.Value : 0,
                    PublisherName = PublisherName
                };
        }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            PublisherModel[] publishers = PublisherApp.MatchPublishers(PublisherName, City);
            if (publishers.Length > 0 && PublisherId != publishers[0].PublisherId)
                yield return new ValidationResult("Publishers must be unique", new string[] { "PublisherName", "City" });
        }
    }
}